import {ref, computed} from 'vue'
import {defineStore} from 'pinia'
import {childrenRouter} from "@/router/router";
import {getUserInfo} from "@/api/user";
import {useRoute, useRouter} from "vue-router";

export const useUserInfoStore = defineStore('xjm_userInfoStore', () => {

        let token = ref('')
        let userInfo: any = ref({})
        let router = ref([])
        let $router = useRouter()
        let $route = useRoute()

        const updateUserInfo = async () => {
            await getUserInfo().then((res: any) => {
                userInfo.value = res.data
            })
        }

        //@ts-ignore
        router.value.push(...childrenRouter)

        //获取用户信息
        //否则验证token有效性
        const selectUserInfo = async () => {
            await getUserInfo().then((res: any) => {
                userInfo.value = res.data
            }).catch((err: any) => {
                token.value = ''
                console.log($route.path)

                $router.push({path: '/login', query: {redirect: $route.path}})
            })
        }

        return {token, userInfo, router, updateUserInfo, selectUserInfo}
    },
    //开启pinia持久化
    {
        persist: {
            paths: ['token', 'userInfo']
        }
    }
)
